﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Collections.Specialized;
namespace XYZshell.Game.CardGameEngine
{
	public class NameFindableCollection<T> : Collection<T>,INotifyPropertyChanged where T : INamed
	{
		public NameFindableCollection()
			: base()
		{

		}
		public NameFindableCollection( IList<T> list )
			: base( list )
		{
			
		}

		/// <summary>
		/// 覆盖式添加
		/// </summary>
		/// <param name="item"></param>
		public  void AddOverride( T item )
		{
			T f=Find(item.Name);
			if (f != null)
				Items.Remove( f );
			base.Add( item );
		}
		/// <summary>
		/// 根据名称从集合中找到指定对象
		/// </summary>
		/// <param name="name">名称</param>
		/// <returns>找到的对象</returns>
		public T this[string name]
		{

			get
			{
				return Find( name );
			}
			set
			{
				T v= Find( name );
				if (v != null)
				{
					v = value;
					return;
				}
				Add( value );

			}
		}

		public T Find( string name )
		{
			try
			{
				T f =Items.First<T>( ( c ) =>
				{
					return c.Name == name;
				} );
				return f;
			}
			catch
			{
				return default(T);
			}
		}

		#region INotifyPropertyChanged implementation
		public event PropertyChangedEventHandler PropertyChanged;
		#endregion
		
		public event EventHandler CollectionChanged;
	}
}
